import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Spin, Alert, Typography, Button, Space, Select, Form, InputNumber, Input } from 'antd';
import { ArrowLeftOutlined, ReloadOutlined, FilterOutlined } from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import 'echarts-gl';

import { stockApi } from '../services/stockApi';

const { Title } = Typography;
const { Option } = Select;

const Stock3DChart = ({ onBack }) => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [stockData, setStockData] = useState([]);
  const [filteredData, setFilteredData] = useState([]);
  const [selectedYear, setSelectedYear] = useState(new Date().getFullYear()); // 默认当前年份
  const [filterVisible, setFilterVisible] = useState(false);
  const [filters, setFilters] = useState({
    minPrice: null,
    maxPrice: null,
    minDividend: null,
    maxDividend: null,
    minShares: null,
    maxShares: null
  });
  
  // 生成年份选项（当前年份及前5年）
  const generateYearOptions = () => {
    const currentYear = new Date().getFullYear();
    const years = [];
    for (let i = 0; i <= 5; i++) {
      years.push(currentYear - i);
    }
    return years;
  };
  
  // 应用筛选条件
  const applyFilters = () => {
    let filtered = [...stockData];
    
    // 应用最高价范围筛选
    if (filters.minPrice !== null) {
      filtered = filtered.filter(item => item.max_price >= filters.minPrice);
    }
    if (filters.maxPrice !== null) {
      filtered = filtered.filter(item => item.max_price <= filters.maxPrice);
    }
    
    // 应用股息范围筛选
    if (filters.minDividend !== null) {
      filtered = filtered.filter(item => item.dividend >= filters.minDividend);
    }
    if (filters.maxDividend !== null) {
      filtered = filtered.filter(item => item.dividend <= filters.maxDividend);
    }
    
    // 应用流通量范围筛选
    if (filters.minShares !== null) {
      filtered = filtered.filter(item => item.liqa_share >= filters.minShares * 100000000);
    }
    if (filters.maxShares !== null) {
      filtered = filtered.filter(item => item.liqa_share <= filters.maxShares * 100000000);
    }
    
    setFilteredData(filtered);
  };
  
  // 重置筛选条件
  const resetFilters = () => {
    setFilters({
      minPrice: null,
      maxPrice: null,
      minDividend: null,
      maxDividend: null,
      minShares: null,
      maxShares: null
    });
    setFilteredData(stockData);
  };
  
  // 当筛选条件变化时，自动应用筛选
  useEffect(() => {
    if (stockData.length > 0) {
      applyFilters();
    }
  }, [filters, stockData]);
  
  // 获取股票数据
  const fetchStockData = async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await stockApi.getAllStocks(selectedYear);
      setStockData(data || []);
      setFilteredData(data || []); // 初始化筛选数据为全部数据
    } catch (err) {
      console.error('获取股票数据失败:', err);
      // 如果API请求失败，使用模拟数据
      console.log('使用模拟数据进行演示');
      const mockData = [
        {
          stock_no: '000001',
          stock_market: 'sz',
          name: '平安银行',
          max_price: 15.68,
          dividend: 0.35,
          liqa_share: 19405918110,
          open_price: 14.20,
          close_price: 14.85
        },
        {
          stock_no: '000002',
          stock_market: 'sz',
          name: '万科A',
          max_price: 18.95,
          dividend: 0.85,
          liqa_share: 9639354645,
          open_price: 17.50,
          close_price: 18.20
        },
        {
          stock_no: '600036',
          stock_market: 'sh',
          name: '招商银行',
          max_price: 35.68,
          dividend: 1.25,
          liqa_share: 20672387665,
          open_price: 34.20,
          close_price: 34.85
        },
        {
          stock_no: '600519',
          stock_market: 'sh',
          name: '贵州茅台',
          max_price: 1685.68,
          dividend: 21.75,
          liqa_share: 1256197800,
          open_price: 1650.20,
          close_price: 1670.85
        },
        {
          stock_no: '000858',
          stock_market: 'sz',
          name: '五粮液',
          max_price: 185.68,
          dividend: 2.55,
          liqa_share: 3868147965,
          open_price: 180.20,
          close_price: 182.85
        },
        {
          stock_no: '600276',
          stock_market: 'sh',
          name: '恒瑞医药',
          max_price: 65.68,
          dividend: 0.95,
          liqa_share: 4145938765,
          open_price: 62.20,
          close_price: 63.85
        },
        {
          stock_no: '300750',
          stock_market: 'sz',
          name: '宁德时代',
          max_price: 285.68,
          dividend: 3.25,
          liqa_share: 2331404165,
          open_price: 280.20,
          close_price: 282.85
        },
        {
          stock_no: '002415',
          stock_market: 'sz',
          name: '海康威视',
          max_price: 45.68,
          dividend: 0.75,
          liqa_share: 9338144165,
          open_price: 42.20,
          close_price: 43.85
        }
      ];
      setStockData(mockData);
      setFilteredData(mockData); // 初始化筛选数据为全部数据
      setError(`注意：当前使用模拟数据 (${selectedYear}年)，请确保后端服务已启动以获取真实数据`);
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时获取数据
  useEffect(() => {
    fetchStockData();
  }, [selectedYear]);

  // 准备三维图表数据
  const get3DChartOption = () => {
    // 过滤有效数据
    const validData = filteredData.filter(item => 
      item.dividend && item.dividend > 0 && 
      item.max_price && item.max_price > 0 &&
      item.liqa_share && item.liqa_share > 0
    );

    // 如果没有有效数据，返回空配置
    if (validData.length === 0) {
      return {
        title: {
          text: '股票三维分析图',
          left: 'center',
          textStyle: {
            fontSize: 18
          }
        },
        xAxis3D: {
          type: 'value',
          name: '流通量(亿股)',
          nameTextStyle: {
            fontSize: 14,
            color: '#333'
          },
          min: 0,
          axisLabel: {
            formatter: '{value}亿'
          }
        },
        yAxis3D: {
          type: 'value',
          name: '分红(元)',
          nameTextStyle: {
            fontSize: 14,
            color: '#333'
          },
          min: 0,
          axisLabel: {
            formatter: '¥{value}'
          }
        },
        zAxis3D: {
          type: 'value',
          name: '最高价(元)',
          nameTextStyle: {
            fontSize: 14,
            color: '#333'
          },
          min: 0,
          axisLabel: {
            formatter: '¥{value}'
          }
        },
        grid3D: {
          boxWidth: 200,
          boxDepth: 80,
          viewControl: {
            projection: 'perspective',
            autoRotate: true,
            autoRotateSpeed: 10,
            distance: 300
          }
        },
        series: [{
          type: 'scatter3D',
          data: [],
          symbolSize: 8,
          itemStyle: {
            opacity: 0.8
          }
        }]
      };
    }

    // 转换数据为图表需要的格式 [流通量(亿股), 分红(元), 最高价(元), 股票名称]
    const chartData = validData.map(item => [
      item.liqa_share / 100000000, // 转换为亿股
      item.dividend,
      item.max_price,
      item.name || `${item.stock_market}.${item.stock_no}`
    ]);

    // 获取最高价的最小值和最大值，用于颜色映射
    const maxPrices = chartData.map(item => item[2]);
    const minPrice = Math.min(...maxPrices);
    const maxPrice = Math.max(...maxPrices);

    return {
      title: {
        text: '股票三维分析图',
        left: 'center',
        textStyle: {
          fontSize: 18
        }
      },
      tooltip: {
        formatter: function(params) {
          const [liqaShare, dividend, maxPrice, name] = params.value;
          return `
            <div>
              <strong>${name}</strong><br/>
              流通量: ${liqaShare.toFixed(2)}亿股<br/>
              分红: ¥${dividend.toFixed(2)}<br/>
              最高价: ¥${maxPrice.toFixed(2)}
            </div>
          `;
        }
      },
      visualMap: {
        show: true,
        dimension: 2, // 使用最高价作为视觉映射维度
        min: minPrice,
        max: maxPrice,
        inRange: {
          color: ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffbf', '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']
        },
        text: ['最高价', ''],
        textStyle: {
          color: '#333'
        },
        calculable: true
      },
      xAxis3D: {
        type: 'value',
        name: '流通量(亿股)',
        nameTextStyle: {
          fontSize: 14,
          color: '#333'
        },
        min: 0,
        axisLabel: {
          formatter: '{value}亿'
        }
      },
      yAxis3D: {
        type: 'value',
        name: '分红(元)',
        nameTextStyle: {
          fontSize: 14,
          color: '#333'
        },
        min: 0,
        axisLabel: {
          formatter: '¥{value}'
        }
      },
      zAxis3D: {
        type: 'value',
        name: '最高价(元)',
        nameTextStyle: {
          fontSize: 14,
          color: '#333'
        },
        min: 0,
        axisLabel: {
          formatter: '¥{value}'
        }
      },
      grid3D: {
        boxWidth: 200,
        boxDepth: 80,
        viewControl: {
          projection: 'perspective',
          autoRotate: true,
          autoRotateSpeed: 10,
          distance: 300
        },
        light: {
          main: {
            intensity: 1.2,
            shadow: true
          },
          ambient: {
            intensity: 0.3
          }
        }
      },
      series: [{
        type: 'scatter3D',
        data: chartData,
        symbolSize: 8,
        itemStyle: {
          opacity: 0.8
        },
        emphasis: {
          itemStyle: {
            opacity: 1
          }
        }
      }]
    };
  };

  return (
    <div>
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Space>
          <Button 
            icon={<ArrowLeftOutlined />} 
            onClick={onBack}
          >
            返回
          </Button>
          <Title level={3} style={{ margin: 0 }}>股票三维分析图表</Title>
        </Space>
        <Space>
          <Select
            value={selectedYear}
            onChange={setSelectedYear}
            style={{ width: 100 }}
            placeholder="选择年份"
          >
            {generateYearOptions().map(year => (
              <Option key={year} value={year}>{year}年</Option>
            ))}
          </Select>
          <Button 
            icon={<FilterOutlined />} 
            onClick={() => setFilterVisible(!filterVisible)}
          >
            {filterVisible ? '隐藏筛选' : '显示筛选'}
          </Button>
          <Button 
            icon={<ReloadOutlined />} 
            onClick={fetchStockData}
            loading={loading}
          >
            刷新数据
          </Button>
        </Space>
      </div>

      {filterVisible && (
        <Card style={{ marginBottom: 16 }}>
          <Form layout="vertical">
            <Title level={4}>数据筛选范围</Title>
            <Row gutter={[16, 16]}>
              <Col xs={24} sm={12} md={8}>
                <Form.Item label="最高价范围 (元)">
                  <Input.Group compact>
                    <InputNumber
                      style={{ width: '50%' }}
                      placeholder="最低价"
                      value={filters.minPrice}
                      onChange={(value) => setFilters({...filters, minPrice: value})}
                      min={0}
                      step={0.01}
                    />
                    <InputNumber
                      style={{ width: '50%' }}
                      placeholder="最高价"
                      value={filters.maxPrice}
                      onChange={(value) => setFilters({...filters, maxPrice: value})}
                      min={0}
                      step={0.01}
                    />
                  </Input.Group>
                </Form.Item>
              </Col>
              <Col xs={24} sm={12} md={8}>
                <Form.Item label="股息范围 (元)">
                  <Input.Group compact>
                    <InputNumber
                      style={{ width: '50%' }}
                      placeholder="最低股息"
                      value={filters.minDividend}
                      onChange={(value) => setFilters({...filters, minDividend: value})}
                      min={0}
                      step={0.01}
                    />
                    <InputNumber
                      style={{ width: '50%' }}
                      placeholder="最高股息"
                      value={filters.maxDividend}
                      onChange={(value) => setFilters({...filters, maxDividend: value})}
                      min={0}
                      step={0.01}
                    />
                  </Input.Group>
                </Form.Item>
              </Col>
              <Col xs={24} sm={12} md={8}>
                <Form.Item label="流通量范围 (亿股)">
                  <Input.Group compact>
                    <InputNumber
                      style={{ width: '50%' }}
                      placeholder="最低流通量"
                      value={filters.minShares}
                      onChange={(value) => setFilters({...filters, minShares: value})}
                      min={0}
                      step={0.01}
                    />
                    <InputNumber
                      style={{ width: '50%' }}
                      placeholder="最高流通量"
                      value={filters.maxShares}
                      onChange={(value) => setFilters({...filters, maxShares: value})}
                      min={0}
                      step={0.01}
                    />
                  </Input.Group>
                </Form.Item>
              </Col>
            </Row>
            <Space>
              <Button onClick={resetFilters}>重置筛选</Button>
              <span style={{ color: '#666' }}>
                当前显示: {filteredData.length} / {stockData.length} 只股票
              </span>
            </Space>
          </Form>
        </Card>
      )}

      {error && (
        <Alert
          message="提示"
          description={error}
          type="warning"
          showIcon
          style={{ marginBottom: 16 }}
        />
      )}

      <Spin spinning={loading}>
        <Card>
          <ReactECharts 
            option={get3DChartOption()} 
            style={{ height: '600px' }}
            notMerge={true}
            lazyUpdate={true}
          />
        </Card>
        
        <Card style={{ marginTop: 16 }}>
          <Title level={4}>图表说明</Title>
          <Row gutter={[16, 16]}>
            <Col xs={24}>
              <p><strong>股票三维分析图：</strong></p>
              <ul>
                <li>X轴：流通量（亿股）</li>
                <li>Y轴：分红（元）</li>
                <li>Z轴：最高价（元）</li>
                <li>点的颜色：根据最高价高低进行渐变显示</li>
                <li>交互功能：支持自动旋转、缩放和鼠标悬停查看详细信息</li>
                <li>数据筛选：通过年份选择器可查看不同年份的数据</li>
                <li>高级筛选：可按最高价、股息和流通量范围筛选股票数据</li>
              </ul>
            </Col>
          </Row>
        </Card>
      </Spin>
    </div>
  );
};

export default Stock3DChart;